<?php
class CatsModel extends RelationModel {
	
	public $_link = array(
			'Post_cat'=> array(
			
					'mapping_type'=>HAS_MANY,
			
					'class_name'=>'Post_cat',
			
					'mapping_name'=>'in_post',
					
					'foreign_key'=>'cat_id',
					//post_user
					'parent_key'=>'cat_id'),
			
			
			'Father'=> array(
						
					'mapping_type'=>HAS_ONE,
						
					'class_name'=>'Cats',
						
					'mapping_name'=>'father',
					
					'mapping_key'=>'cat_father',
					
					'foreign_key'=>'cat_father',
					
					'parent_key'=>'cat_id'),
	);
	

    public function category() {
      import("@.ORG.Category");

       $Cat = new Category('Cats',array('cat_id', 'cat_father', 'cat_name', 'cat_slug'));//, array('cid', 'pid', 'name', 'fullname')
            
       return $Cat->getList();              
        
           
    }
    
    public function mass_del($cat_id,$child=false){
    	if (is_array($cat_id)) {
    		foreach ($cat_id as $id){
    			$this->del($id,$child);
    		};
    	}else {
    		$this->del($cat_id,$child);
    	}
    	
    }
	
    public function del($cat_id,$child=false) {
    	import("@.ORG.Category");
    
    	$Cat = new Category('Cats',array('cat_id', 'cat_father', 'cat_name', 'cat_slug'));//, array('cid', 'pid', 'name', 'fullname')
    
    	if ($child) {
    		D('Cats')->where(array('cat_father'=>$cat_id))->relation(true)->delete();
    	}else {
    		D('Cats')->where(array('cat_father'=>$cat_id))->setField('cat_father',0);
    	}
    	return $Cat->del($cat_id);
    }
    
    
    public function child($cat_id){
    
    	$children=D ( 'Cats' )->where(array('cat_father'=>$cat_id))->select();
    	
    	return $children;
    }
    
    public function childen($cat_id){
    
    	$children=D ( 'Cats' )->where(array('cat_father'=>$cat_id))->select();
    	foreach ($children as $key=>$value){
    		if ($this->has_child($value[cat_id])) {
    			$children[$key]['child']=$this->childen($value[cat_id]);
    		}
    	} 
    	
    	return $children;
    }
    
    public function has_child($cat_id){
    
    	$children=D ( 'Cats' )->where(array('cat_father'=>$cat_id))->count();
    	
    	if ($children==0) {
    		return false;
    	}else {
    		return true;
    	}
    }
    
    public function fathers($cat_id){
    	$Cats=D ( 'Cats' );
    	$cat=$this->detail($cat_id);
    	
    	$father=$this->detail($cat['cat_father']);
    	
    	//@TODO .....
    	 
    	return $father;
    }
    
    public function detail($cat_id) {
    	
    	$cat=D ( 'Cats' )->where(array('cat_id'=>$cat_id))->find();
    	
    	return $cat;
    }
    
    public function get_posts($cat_id) {
    	 
    	$cat=D ( 'Post_cat' )->field('post_id')->where(array('cat_id'=>$cat_id))->select();
		
		foreach ($cat as $key => $value) {
			$cat[$key]=$cat[$key]['post_id'];
		}
    	
    	return $cat;
    }
    
	
}